<template>
  <div class="system-log-container">
    <!-- 搜索区域 -->
    <div class="search-box">
      <el-input
          v-model="content"
          placeholder="请输入日志内容"
          style="width: 200px"
          clearable
          prefix-icon="Search"
      ></el-input>

      <el-select
          v-model="level"
          placeholder="选择日志级别"
          style="width: 150px; margin-left: 10px"
          clearable
      >
        <el-option label="全部级别" value="">
          <span>📋 全部日志</span>
        </el-option>
        <el-option label="INFO" value="INFO">
          <span style="color: #67C23A">✅ INFO - 信息</span>
        </el-option>
        <el-option label="WARN" value="WARN">
          <span style="color: #E6A23C">⚠️ WARN - 警告</span>
        </el-option>
        <el-option label="ERROR" value="ERROR">
          <span style="color: #F56C6C">❌ ERROR - 错误</span>
        </el-option>
      </el-select>

      <el-input
          v-model="module"
          placeholder="模块名称"
          style="width: 200px; margin-left: 10px"
          clearable
          prefix-icon="Files"
      ></el-input>

      <el-button
          type="primary"
          style="margin-left: 10px"
          @click="load"
          icon="Search"
      >
        查询
      </el-button>

      <el-button
          type="warning"
          style="margin-left: 5px"
          @click="reset"
          icon="RefreshRight"
      >
        重置
      </el-button>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-container">
      <el-card class="stat-card stat-info" shadow="hover" @click="filterByLevel('INFO')">
        <div class="stat-content">
          <div class="stat-icon">✅</div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.infoCount }}</div>
            <div class="stat-label">INFO 日志</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card stat-warn" shadow="hover" @click="filterByLevel('WARN')">
        <div class="stat-content">
          <div class="stat-icon">⚠️</div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.warnCount }}</div>
            <div class="stat-label">WARN 日志</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card stat-error" shadow="hover" @click="filterByLevel('ERROR')">
        <div class="stat-content">
          <div class="stat-icon">❌</div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.errorCount }}</div>
            <div class="stat-label">ERROR 日志</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card stat-total" shadow="hover" @click="filterByLevel('')">
        <div class="stat-content">
          <div class="stat-icon">📊</div>
          <div class="stat-info">
            <div class="stat-value">{{ total }}</div>
            <div class="stat-label">总日志数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="action-box">
      <el-button
          type="danger"
          @click="delBatch"
          :disabled="multipleSelection.length === 0"
          icon="Delete"
      >
        批量删除 ({{ multipleSelection.length }})
      </el-button>

      <el-popconfirm
          title="确定清空所有日志吗？此操作不可恢复！"
          @confirm="clearAll"
          confirm-button-text="确定清空"
          cancel-button-text="取消"
      >
        <template #reference>
          <el-button type="danger" plain icon="DeleteFilled">
            清空全部日志
          </el-button>
        </template>
      </el-popconfirm>
    </div>

    <!-- 表格区域 -->
    <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
    >
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="id" label="ID" width="70" align="center"></el-table-column>

      <el-table-column prop="level" label="级别" width="120" align="center">
        <template #default="scope">
          <el-tag
              :type="getLevelType(scope.row.level)"
              effect="dark"
              size="large"
              class="level-tag"
          >
            <span class="level-icon">{{ getLevelIcon(scope.row.level) }}</span>
            {{ scope.row.level }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="module" label="模块" width="180">
        <template #default="scope">
          <el-text tag="b" type="primary">{{ scope.row.module }}</el-text>
        </template>
      </el-table-column>

      <el-table-column prop="operation" label="操作" width="150"></el-table-column>

      <el-table-column prop="content" label="日志内容" min-width="250" show-overflow-tooltip>
        <template #default="scope">
          <span :class="'content-' + scope.row.level.toLowerCase()">
            {{ scope.row.content }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="userName" label="用户" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.userName" type="info" size="small">
            👤 {{ scope.row.userName }}
          </el-tag>
          <span v-else style="color: #ccc">-</span>
        </template>
      </el-table-column>

      <el-table-column prop="ip" label="IP地址" width="140" align="center">
        <template #default="scope">
          <el-text type="info" size="small">🌐 {{ scope.row.ip }}</el-text>
        </template>
      </el-table-column>

      <el-table-column prop="executionTime" label="耗时" width="100" align="center">
        <template #default="scope">
          <el-tag
              :type="getTimeType(scope.row.executionTime)"
              size="small"
          >
            ⏱️ {{ scope.row.executionTime }}ms
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="时间" width="180" align="center"></el-table-column>

      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
<!--          <el-button-->
<!--              size="small"-->
<!--              @click="handleView(scope.row)"-->
<!--              icon="View"-->
<!--              type="primary"-->
<!--              link-->
<!--          >-->
<!--            详情-->
<!--          </el-button>-->

          <el-popconfirm
              title="确定删除这条日志吗？"
              @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button
                  size="small"
                  type="danger"
                  icon="Delete"
                  link
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog
        title="📋 日志详情"
        v-model="dialogVisible"
        width="70%"
    >
      <el-descriptions :column="2" border size="large">
        <el-descriptions-item label="日志ID">
          <el-tag>{{ currentLog.id }}</el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="日志级别">
          <el-tag
              :type="getLevelType(currentLog.level)"
              effect="dark"
              size="large"
          >
            {{ getLevelIcon(currentLog.level) }} {{ currentLog.level }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="所属模块">
          <el-text tag="b" type="primary">{{ currentLog.module }}</el-text>
        </el-descriptions-item>

        <el-descriptions-item label="操作名称">
          {{ currentLog.operation }}
        </el-descriptions-item>

        <el-descriptions-item label="方法路径" :span="2">
          <el-text type="info" size="small">{{ currentLog.method }}</el-text>
        </el-descriptions-item>

        <el-descriptions-item label="操作用户">
          <el-tag v-if="currentLog.userName" type="success">
            👤 {{ currentLog.userName }}
          </el-tag>
          <span v-else style="color: #ccc">未知用户</span>
        </el-descriptions-item>

        <el-descriptions-item label="IP地址">
          <el-text type="warning">🌐 {{ currentLog.ip }}</el-text>
        </el-descriptions-item>

        <el-descriptions-item label="执行时长">
          <el-tag :type="getTimeType(currentLog.executionTime)">
            ⏱️ {{ currentLog.executionTime }} 毫秒
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="记录时间">
          🕐 {{ currentLog.createTime }}
        </el-descriptions-item>

        <el-descriptions-item label="日志内容" :span="2">
          <el-alert
              :type="getLevelType(currentLog.level)"
              :closable="false"
          >
            {{ currentLog.content }}
          </el-alert>
        </el-descriptions-item>

        <el-descriptions-item label="请求参数" :span="2">
          <pre class="params-box">{{ currentLog.params || '无参数' }}</pre>
        </el-descriptions-item>

        <el-descriptions-item
            label="异常信息"
            :span="2"
            v-if="currentLog.exceptionInfo"
        >
          <el-alert type="error" :closable="false">
            <pre class="exception-info">{{ currentLog.exceptionInfo }}</pre>
          </el-alert>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "SystemLog",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      level: "",
      module: "",
      content: "",
      multipleSelection: [],
      dialogVisible: false,
      currentLog: {},
      stats: {
        infoCount: 0,
        warnCount: 0,
        errorCount: 0
      }
    }
  },
  created() {
    this.load()
    this.loadStats()
  },
  methods: {
    // 加载数据
    load() {
      request.get("/systemLog/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          level: this.level,
          module: this.module,
          content: this.content
        }
      }).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },

    // 加载统计数据
    loadStats() {
      // INFO 统计
      request.get("/systemLog/page", {
        params: {pageNum: 1, pageSize: 1, level: 'INFO'}
      }).then(res => {
        if (res.code === '200') {
          this.stats.infoCount = res.data.total
        }
      })

      // WARN 统计
      request.get("/systemLog/page", {
        params: {pageNum: 1, pageSize: 1, level: 'WARN'}
      }).then(res => {
        if (res.code === '200') {
          this.stats.warnCount = res.data.total
        }
      })

      // ERROR 统计
      request.get("/systemLog/page", {
        params: {pageNum: 1, pageSize: 1, level: 'ERROR'}
      }).then(res => {
        if (res.code === '200') {
          this.stats.errorCount = res.data.total
        }
      })
    },

    // 获取级别对应的类型
    getLevelType(level) {
      const typeMap = {
        'INFO': 'success',
        'WARN': 'warning',
        'ERROR': 'danger'
      }
      return typeMap[level] || 'info'
    },

    // 获取级别对应的图标
    getLevelIcon(level) {
      const iconMap = {
        'INFO': '✅',
        'WARN': '⚠️',
        'ERROR': '❌'
      }
      return iconMap[level] || '📝'
    },

    // 根据执行时间返回标签类型
    getTimeType(time) {
      if (time < 100) return 'success'    // 快速
      if (time < 500) return 'warning'    // 正常
      return 'danger'                      // 慢速
    },

    // 表格行样式
    tableRowClassName({row}) {
      if (row.level === 'ERROR') {
        return 'error-row'
      } else if (row.level === 'WARN') {
        return 'warning-row'
      }
      return ''
    },

    // 通过级别筛选
    filterByLevel(level) {
      this.level = level
      this.pageNum = 1
      this.load()
    },

    // 重置搜索
    reset() {
      this.level = ""
      this.module = ""
      this.content = ""
      this.pageNum = 1
      this.load()
    },

    // 查看详情
    handleView(row) {
      this.currentLog = row
      this.dialogVisible = true
    },

    // 删除单条
    handleDelete(id) {
      request.delete("/systemLog/" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("删除成功")
          this.load()
          this.loadStats()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 批量删除
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)
      request.post("/systemLog/del/batch", ids).then(res => {
        if (res.code === '200') {
          this.$message.success("批量删除成功")
          this.load()
          this.loadStats()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 清空所有日志
    clearAll() {
      request.delete("/systemLog/clear").then(res => {
        if (res.code === '200') {
          this.$message.success("清空成功")
          this.load()
          this.loadStats()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.load()
    }
  }
}
</script>

<style scoped>
.system-log-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.search-box {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 统计卡片容器 */
.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  font-size: 48px;
  line-height: 1;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

/* 不同级别的统计卡片颜色 */
.stat-info {
  border-left: 4px solid #67C23A;
}

.stat-info .stat-value {
  color: #67C23A;
}

.stat-warn {
  border-left: 4px solid #E6A23C;
}

.stat-warn .stat-value {
  color: #E6A23C;
}

.stat-error {
  border-left: 4px solid #F56C6C;
}

.stat-error .stat-value {
  color: #F56C6C;
}

.stat-total {
  border-left: 4px solid #409EFF;
}

.stat-total .stat-value {
  color: #409EFF;
}

/* 操作按钮区域 */
.action-box {
  margin-bottom: 10px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 级别标签样式 */
.level-tag {
  font-weight: bold;
}

.level-icon {
  margin-right: 5px;
}

/* 日志内容颜色 */
.content-info {
  color: #67C23A;
}

.content-warn {
  color: #E6A23C;
  font-weight: 500;
}

.content-error {
  color: #F56C6C;
  font-weight: bold;
}


/* 详情对话框中的代码块 */
.params-box,
.exception-info {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.6;
  max-height: 300px;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.exception-info {
  color: #d9534f;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-container {
    grid-template-columns: 1fr;
  }
}
</style>
